package com.xt.base.action;

import java.io.BufferedOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.xt.base.dao.hibernate.HiberSessionHolder;
import com.xt.base.model.base.BlobDATA;

public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 6688190056757256487L;
	private static Logger log = Logger.getLogger(DownloadServlet.class);

	public DownloadServlet() {

	}

	public void init() throws ServletException {
	}

	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String code = request.getParameter("code");
		String inline = request.getParameter("inline");
		String type = null;
		if(StringUtils.isEmpty(inline)){
			type = "attachment;filename=\"";
		}else{
			type = "inline;filename=\"";
		}
		
		
		try {
			Session session = HiberSessionHolder.getReadOnlySession();
			BlobDATA blobDATA = (BlobDATA) session.get(BlobDATA.class, code);
			log.info("Get file , its code is " + code + ",its file name is "
					+ blobDATA.getTitle());
			if(StringUtils.isNotEmpty(blobDATA.getTitle())){
				type += new String(blobDATA.getTitle().getBytes(),"ISO8859-1");
			}
			response.setHeader("Content-disposition",type+"\"" );
			//response.setHeader("Content-Type", blobDATA.getTitle());
			//response.setHeader("Content-Length", String.valueOf(blobDATA.getBytes().length));
			BufferedOutputStream out = new BufferedOutputStream(response
					.getOutputStream());
			out.write(blobDATA.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			HiberSessionHolder.closeSession();
		}
	}

}
